package org.ruanjj.multithread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

//创建线程的第三种方式 Callable实现类
public class ThreadDemo3 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        PrintEven printEven = new PrintEven();
        FutureTask futureTask = new FutureTask(printEven);

        Thread t1 = new Thread(futureTask);
        t1.start();

        FutureTask futureTask1 = new FutureTask(()->{
            System.out.println(Thread.currentThread().getName() + "正在执行。。。");
            int i = 1;
            while(i < 100){
              i = i*2;
            }
            System.out.println(Thread.currentThread().getName() + "执行完成");
            return i;
        });
        Thread t2 = new Thread(futureTask1,"AA");
        Thread t3 = new Thread(futureTask1,"BB");

        t2.start();
        t3.start();

        System.out.println(futureTask1.get());
        System.out.println("执行结束");
    }
}

class PrintEven implements Callable{

    @Override
    public Object call() throws Exception {
        int sum = 0;
        for(int i = 0; i < 100; i++){
            if(i % 2 == 0){
                System.out.println(i);
                sum += i;
            }
        }
        return sum;
    }
}
